package asc;

class Utf8 {

	var __b : Array<String>;

	public function new( ?size : Int ) {
		__b = [];
	}

	public function addChar( c : Int ) {
		__b.push(String.fromCharCode(c));
	}

	public function toString() {
		return __b.join("");
	}

	public static function encode( s : String ) : String {
		return untyped __js__("unescape( encodeURIComponent( s ) )");
	}

	public static function decode( s : String ) : String {
		return untyped __js__("decodeURIComponent( escape( s ) )");
	}

	public static function iter( s : String, chars : Int -> Void ) {
		for (i in 0...s.length)
			chars(s.charCodeAt(i));
	}

	public static function charCodeAt( s : String, index : Int ) : Int {
		return s.charCodeAt(index);
	}

	public static function validate( s : String ) : Bool
	{
		var l = s.length;
		while( l-- > 0 ) {
			var c = s.charCodeAt(l);
			if( c < 0x7F )
				continue;
			else if( c < 0xC0 )
				return false;
			else if( c < 0xE0 ) {
				if( (s.charCodeAt(--l) & 0x80) != 0x80 )
					return false;
			} else if( c < 0xF0 ) {
				if( (s.charCodeAt(--l) & 0x80) != 0x80 )
					return false;
				if( (s.charCodeAt(--l) & 0x80) != 0x80 )
					return false;
			} else {
				if( (s.charCodeAt(--l) & 0x80) != 0x80 )
					return false;
				if( (s.charCodeAt(--l) & 0x80) != 0x80 )
					return false;
				if( (s.charCodeAt(--l) & 0x80) != 0x80 )
					return false;
			}
		}
		return true;
	}

	public static function length( s : String ) : Int
	{
		return s.length;
	}

	public static function compare( a : String, b : String ) : Int {
		return if (a > b) 1;
			else if (a < b) -1;
			else 0;
	}

	public static function sub( s : String, pos : Int, len : Int ) : String {
		return s.substr(pos, len);
	}
}